#include "database.h"
#include <sqlite3.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
extern sqlite3 *ppDb;  
void sqlite3_init()
{

      if(sqlite3_open("user.db", &ppDb)!=SQLITE_OK)
      {

         printf("sqlite3 fail %s\n",sqlite3_errmsg(ppDb));

      }
 
      char sql[128]={0};


      sprintf(sql,"create table if no exist user(user text, password text)");


      if(sqlite3_exec(ppDb,sql,NULL,NULL,NULL)!=SQLITE_OK)
      {

         printf("sqlite3_exec fail %s\n",sqlite3_errmsg(ppDb));

      }
   



}
uint8_t sqlite3_user_exist(const char*name)
{
    char sql[128]={0};
    sprintf(sql,"select user from user;");
    char** result;
    int row;
    int col;
    char* errmsg;
    if( sqlite3_get_table(ppDb,sql,&result,&row,&col,&errmsg)!=SQLITE_OK)
    {

     printf("[ERROR] sqlite_get_table %s\n",errmsg);
     return 0;


    }
     for(int i=0;i<row;i++)
    {
       if(!strcmp(result[i+col],name))
        {return 1;}
    }

    sqlite3_free_table(result);
   return 0;

}
void sqlite3_insert(const char*username,const char*password)
{

   char sql[128]={0};

   sprintf(sql,"insert into user values ('%s','%s');",username,password);
   printf("插入成功\r\n");

   if(sqlite3_exec(ppDb,sql,NULL,NULL,NULL)!=SQLITE_OK)
   {
      cout<<"insert err"<<endl;

   }


}
int sqlite3_login_comp(const char*username,const char*password)
{

    

   
     int flag=0;
     char sql[128]={0};
    sprintf(sql,"select password from user where user='%s';",username);
               
    char** result;
    int row;
    int col;
    char* errmsg;
    if( sqlite3_get_table(ppDb,sql,&result,&row,&col,&errmsg)!=SQLITE_OK)
    {

     printf("[ERROR] sqlite_get_table %s\n",errmsg);
     return 0;


    }

    if(!strcmp(result[1],password))
    {

     flag=1;



    }
       sqlite3_free_table(result);
       return flag;
}